#!/usr/bin/python
# coding=utf8
#
# Copyright (C) 2011 XNData contributors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


__author__ = "zhangchitc@gmail.com"


import cookielib
import urllib2, urllib
from xndata.frontend import LoginPageFetcher
from xndata.frontend import LoginPageParser



class LoginError (Exception):
    
    def __init__ (self, uname):
        self.username = uname

    def __repr__ (self):
        return "Your account is [%s] , please check your password" % self.username

    def __str__ (self):
        return self.__repr__ ()



class XNClient:

    USER_AGENT = "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.5) Gecko/20031107 Debian/1.5-3"
    ACCEPT = "text/html, image/jpeg, image/png, text/*, image/*, */*"
    
    cookie_jar = None
    # urllib2 opener is setup only once when XNClient was created
    opener = None
    user_id = ""
    user_name = ""

    def __init__ (self, uname, upass):
        
        # Setup urllib2 opener for future call
        self.cookie_jar = cookielib.LWPCookieJar()
        self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cookie_jar))
        # camouflaged as mozilla firefox browser
        self.opener.addheaders = [("User-agent", self.USER_AGENT), ("Accept", self.ACCEPT)]
        
        page_html = LoginPageFetcher.fetch_login_page (self.opener, uname, upass)
        parse_result = LoginPageParser.parse_login_page (page_html)
         
        if parse_result["login_state"] == False:
            raise LoginError (uname)

        self.user_id = parse_result["user_id"]
        self.user_name = parse_result["user_name"]

